package rxhttpext


import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import com.google.gson.stream.JsonReader
import rxhttp.wrapper.utils.GsonUtil
import java.io.StringReader
import java.lang.reflect.Type

/**
 * 转换工具类
 */
object Converter {

    val gson: Gson get() = GsonUtil.buildGson()

    /**
     * Json转JsonElement
     *
     * @param json
     * @return
     * @throws Throwable
     */
    @Throws(Throwable::class)
    fun toJsonElement(json: String?): JsonElement {
        val jsonReader = JsonReader(StringReader(json))
        return JsonParser.parseReader(jsonReader)
    }

    /**
     * JsonElement转bean
     * @param json JsonElement
     * @param typeOfT Type
     * @return T
     */
    @Throws(Throwable::class)
    fun <T> toBean(json: JsonElement, typeOfT: Type): T {
        return gson.fromJson(json, typeOfT)
    }

    /**
     * JsonElement转bean
     * @receiver JsonElement
     * @return T
     */
    inline fun <reified T> JsonElement.toBean(): T {
        return gson.fromJson(this, T::class.java)
    }

}